package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.core.mq.ActionType;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.CompanyMapper;
import com.sd365.permission.centre.entity.Company;
import com.sd365.permission.centre.pojo.dto.CompanyDTO;
import com.sd365.permission.centre.pojo.query.CompanyQuery;
import com.sd365.permission.centre.pojo.query.IdVersionQuery;
import com.sd365.permission.centre.service.CompanyService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import com.sd365.permission.centre.service.util.SendMQMessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @Author jxd
 * @Date 2020/12/12  12:59 下午
 * @Version 1.0
 * @Write For CompanyServiceImpl
 * @Email waniiu@126.com
 */
@Service
public class CompanyServiceImpl extends AbstractBaseDataServiceImpl implements CompanyService {


    @Autowired
    private SendMQMessageUtil sendMQMessageUtil;
    private static final String TABLE_NAME = "company";


    @Resource
    CompanyMapper companyMapper;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public List<Company> commonQuery(CompanyQuery companyQuery) {
        try {
            List<Company> companies = companyMapper.commonQuery(companyQuery);
            Page page = (Page) companies;
            BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
            return companies;
        } catch (Exception e) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_COMPANY_COMMONQUERY_EXCEPTION_CODE, e);
        }
    }


    @Override
    public Boolean add(@Valid CompanyDTO companyDTO) {
        Company company = BeanUtil.copy(companyDTO, Company.class);
        company.setId(idGenerator.snowflakeId());
        company.setVersion(1L);
        baseDataStuff4Add(company);

        Boolean flag=companyMapper.insertCompany(company)>0;
        if (flag) {
            sendMQMessageUtil.SendMessage(ActionType.INSERT, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, company);
        }
        return flag;
    }

    /**
     * @param id      公司id
     * @param version 版本
     * @return \\
     * @author Yan Huazhi
     * @date 2020/12/17 11:46
     * @version 0.0.1
     */
    @Override
    public Boolean remove(Long id, Long version) {
        Example example = new Example(Company.class);
        example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
        try {
            Boolean flag = companyMapper.deleteByExample(example) > 0;
            if (flag) {
                Company company = new Company();
                company.setId(id);
                company.setVersion(version);
                sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, company);
            }
            return flag;
        } catch (Exception e) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_COMPANY_REMOVE_EXCEPTION_CODE, e);
        }
    }

    /**
     * 批量删除Company
     *
     * @param idVersionQueryList Company批量删除列表
     * @return
     * @author Yan Huazhi
     * @date 2020/12/17 11:47
     * @version 0.0.1
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeBatch(List<IdVersionQuery> idVersionQueryList) {
        try {
            for (IdVersionQuery idVersionQuery : idVersionQueryList) {
                remove(idVersionQuery.getId(), idVersionQuery.getVersion());
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_COMPANY_REMOVE_BATCH_EXCEPTION_CODE, e);
        }
        return true;
    }

    @Override
    public Boolean modify(CompanyDTO companyDTO) {
        Company company = BeanUtil.copy(companyDTO, Company.class);
        baseDataStuff4Updated(company);
        Example example = new Example(Company.class);
        example.createCriteria().andEqualTo("id", companyDTO.getId()).andEqualTo("version", companyDTO.getVersion());
        company.setUpdatedTime(new Date());
        Boolean flag = companyMapper.updateCompany(company) > 0;
        if (flag) {
            sendMQMessageUtil.SendMessage(ActionType.UPDATE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, company);
        }
        return flag;
    }

    @Override
    public Boolean batchModify(CompanyDTO companyDTO) {
        companyDTO.setUpdatedTime(new Date());
        Company company = BeanUtil.copy(companyDTO, Company.class);
        baseDataStuff4Updated(company);
        Example example = new Example(Company.class);
        example.createCriteria().andEqualTo("id", companyDTO.getId()).andEqualTo("version", companyDTO.getVersion());
        return companyMapper.updateByExampleSelective(company, example) > 0;
    }


    @Override
    public CompanyDTO queryById(Long id) {
        try {
            CompanyDTO companyDTO = null;
            Company company = companyMapper.selectById(id);
            if (company != null) {
                companyDTO = BeanUtil.copy(company, CompanyDTO.class);
            }
            return companyDTO;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        }
    }

    /**
     * 拷贝company记录
     *
     * @param id 公司id
     * @return CompanyDTO
     * @author Yan Huazhi
     * @date 2020/12/17 13:02
     * @version 0.0.1
     */
    @Override
    public CompanyDTO copy(Long id) {
        try {
            Company company = companyMapper.selectById(id);
            if (company != null) {
                CompanyDTO companyDTO = BeanUtil.copy(company, CompanyDTO.class);
                return companyDTO;
            }
        } catch (Exception e) {

        }
        return null;
    }
}
